package com.zahidq.nio;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketOption;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * Created with IntelliJ IDEA.
 * <p/>
 * User: zahid
 * Date: 17/03/13
 */
public class TcpServer implements Runnable{

    Logger logger = Logger.getLogger(TcpServer.class);

    private final TcpConfig tcpConfig;
    private final TcpServerHandler tcpServerHandler;

    private SocketChannel socketChannel;
    private AsynchronousSocketChannel worker;

    public TcpServer(TcpConfig tcpConfig, TcpServerHandler tcpServerHandler) {
        logger.info("#TcpServer " + tcpConfig);
        this.tcpConfig = tcpConfig;
        this.tcpServerHandler = tcpServerHandler;
    }

    @Override
    public void run() {
        logger.info("#run");
        ByteBuffer byteBuffer = tcpConfig.isUseDirectByteBuffers() ?
                ByteBuffer.allocateDirect(tcpConfig.getReceiveByteBufferSize()) :
                ByteBuffer.allocate(tcpConfig.getReceiveByteBufferSize());

        if (tcpConfig.isUseSyncNio()) {
            try {
                ServerSocketChannel serverSocketChannel = ServerSocketChannel.open().bind(new InetSocketAddress(tcpConfig.getPort()));
                socketChannel = serverSocketChannel.accept();
                socketChannel.configureBlocking(true);
                socketChannel.setOption(StandardSocketOptions.TCP_NODELAY,true);
                do {
                    int read = socketChannel.read(byteBuffer);
                    if (read > 0) {
                        tcpServerHandler.onData(this, byteBuffer);
//                        byteBuffer.flip();
//                        socketChannel.write(byteBuffer);
//                        byteBuffer.flip();
                    }
                } while ( ! Thread.currentThread().isInterrupted());
            } catch (IOException e) {
                logger.warn("#run caught" + e.getMessage());
            }

        } else {
            try {
                AsynchronousServerSocketChannel asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(tcpConfig.getPort()));
                Future<AsynchronousSocketChannel> future = asynchronousServerSocketChannel.accept();
                AsynchronousSocketChannel worker = future.get();
                worker.setOption(StandardSocketOptions.TCP_NODELAY,true);
                do {
                    byteBuffer.clear();
                    worker.read(byteBuffer).get();
                    if (byteBuffer.position() > 0) {
                        tcpServerHandler.onData(this, byteBuffer);
//                        byteBuffer.flip();
                        worker.write(byteBuffer).get();
//                        byteBuffer.flip();
                    }
                } while (! Thread.currentThread().isInterrupted());
                worker.close();
                asynchronousServerSocketChannel.close();
            } catch (Exception e) {
                logger.error("#run caught: " + e.getMessage());
            }

        }
        logger.info("#run finished");

    }

    public void sendData(ByteBuffer data) throws IOException, ExecutionException, InterruptedException {
        if (tcpConfig.isUseSyncNio()) {
            socketChannel.write(data);
        } else {
            worker.write(data).get();
        }
    }
}
